package com.aaa.book_mall.controller;

import com.aaa.book_mall.dao.MenuDao;
import com.aaa.book_mall.entity.Menu;
import com.aaa.book_mall.entity.Staff;
import com.aaa.book_mall.util.Tree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName MenuController
 * @Description ToDo
 * @Auther teacher Bai
 * @Date 2021/1/19 9:29
 */
@Controller
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private MenuDao menuDao;

    /**
     * 用于展示左侧导航菜单信息，根据当前登录人的角色id查询
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/getAllMenuByRId")
    public String getAllMenuByRId(HttpServletRequest request, Model model){
        //1。获取到session中存储的当前登录人的角色rid
        HttpSession session = request.getSession();
        Staff staff = (Staff) session.getAttribute("staff");
        Integer roleId = staff.getRoleId();
        List<Menu> menus = menuDao.getAllMenuByRid(roleId);
        //将得到的数据放在请求域对象中
        model.addAttribute("menus",menus);
        return "forward:/rescoues/homePage.jsp";
    }

    /**
     * 获取所有的菜单信息 用于修改权限时的展示全部菜单
     * @return
     */
    @RequestMapping("getAllMenu")
    @ResponseBody
    public List<Tree> getAllMenu(){
        List<Tree> trees = menuDao.getAllMenu();
        //System.out.println(trees);
        return trees;
    }

    /**
     * 根据rid查询对应的所有的mid,用于修改权限时的  回显
     * @param rid
     * @return
     */
    @RequestMapping("getAllMidByRid")
    @ResponseBody
    public List getAllMidByRid(Integer rid){
        List list = menuDao.getAllMidByRid(rid);
        System.out.println(list);
        return list;
    }

    @RequestMapping("editPremission")
    @ResponseBody
    public Map editPremission(Integer rid,String midArr){
        //将前台传来的midArr字符串  转成数组
        String[] split = midArr.split(",");
        //System.out.println(Arrays.toString(split));
        //修改权限的数据操作
        /**
         * 先将角色和权限菜单的中间表中所有当前rid对应的数据删除掉，在根据前台传来的数据重新添加
         */
        int i = menuDao.updatePre(rid, split);
        HashMap<Object, Object> map = new HashMap<>();
        if(i>0){
            map.put("code","1");
            map.put("msg","修改成功");
        }else{
            map.put("code","0");
            map.put("msg","修改失败");
        }
        return map;
    }
}
